<?php

namespace app\lib\api;




use app\lib\exception\ParameterException;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    public function goCheck($completeMatching = false)
    {
        $params = Request::instance()->param();
        if (!$this->batch()->check($params)) {
            throw new ParameterException([
                'msg' => is_array($this->error) ? implode(
                    ';', $this->error) : $this->error,
                'code' => 422
            ]);
        }
        if ($completeMatching) {
            return $this->getCompleteValidateData($params);
        } else {
            return $this->getValidateData($params);
        }
    }

    public function getCompleteValidateData($params)
    {
        $data = [];
        foreach ($this->rule as $k => $v) {
            if (array_key_exists($k, $params)) {
                $data[$k] = $params[$k];
            } else {
                $data[$k] = null;
            }
        }
        return $data;
    }

    public function getValidateData($params)
    {
        $data = [];
        foreach ($this->rule as $k => $v) {
            if (array_key_exists($k, $params)) {
                $data[$k] = $params[$k];
            }
        }
        return $data;
    }


    //判断正整数
    protected function isPositiveInteger($value)
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        }
        return false;
    }

    protected function isArray($value)
    {
        if (is_array(json_decode($value))) {
            return true;
        }
        return false;
    }

    protected function phone($value)
    {
        if (preg_match("/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[01235678]|9[026789])\d{8}$/", $value)) {
            return true;
        }
        return false;
    }

    protected function anything($value)
    {
        return true;
    }
}